package com.example.common.networkutil

import com.example.common.tools.LogUtils
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter

class MyResponseBodyConverter<T> : Converter<ResponseBody, T> {
    private var adapter: TypeAdapter<T>? = null

    constructor(adapter: TypeAdapter<T>) {
        this.adapter = adapter
    }

    override fun convert(value: ResponseBody): T? {
        val jsonString = value.string()
        LogUtils.eLog("http","Response接收数据 ----------》 $jsonString")
        val jsonObject = JSONObject(jsonString)
        val code = jsonObject.getInt("code")
        if (code == 500) {
            var data = jsonObject.opt("data")
            if (data == null) {
                data = "请求异常"
            }
            var map = HashMap<String, Any>()
            map["error"] = data
            jsonObject.put("data", map)
        }
        //正确返回整个json
        return adapter!!.fromJson(jsonString)
    }
}

